<template>
	<view class="message">
		<view class="data" v-for="item in List" :key="item._id" @click="toMessage(item)">
			<view class="image">
				<view class="tip" v-if="!item.tip == 0">
					{{item.tip}}
				</view>
				<image :src="item.avater" mode="" class="img"></image>
			</view>
			<view class="right">
				<view class="top">
					<text class="tex">{{item.name}}</text>
					<text class="time">{{Datas(item.lastTime)}}</text>
				</view>
				<view class="bottom">
					<text>{{item.msg}}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
	} from '@dcloudio/uni-app'
	import {
		onMounted,
		ref
	} from 'vue';
	import datas from '@/pages/tabbar/tabbar-4/datas.js'
	import myfun from '@/pages/tabbar/tabbar-4/myfun.js'
	const List = ref([])
	const userid = ref('')
	// websocket信息存储
	var socketOpen = false;
	var socketMsgQueue = [];
	onMounted(() => {
		// List.value = datas.frineds()
		getFrineds()
		// 获取用户信息
		
	})
	onLoad(() => {
		let userId = uni.getStorageSync("userinfo")._id
		uni.connectSocket({
			url: 'ws://127.0.0.1:8082/' + userId,
			success: data => {
				console.log(data);
			}
		})
		uni.onSocketOpen(function(res) {
			socketOpen = true;
			for (var i = 0; i < socketMsgQueue.length; i++) {
				sendSocketMessage(socketMsgQueue[i]);
			}
			socketMsgQueue = [];
		});
		uni.onSocketClose(function(res) {
			console.log('WebSocket 已关闭！');
		});
		uni.onSocketError(function(res) {
			console.log('WebSocket连接打开失败，请检查！');
		});
		receiveSocketMsg()
	})
	// 处理时间
	const Datas = (data) => {
		return myfun.dateTime(data)
	}
	// 跳转详情页
	const toMessage = (data) => {
		// console.log(data);
		// uni.navigateTo({
		// 	url: "/pages/tabbar/tabbar-4/chat/chat?id=" + id
		// })
		uni.navigateTo({
			url: "/pages/tabbar/tabbar-4/chat/chat?id=" + data.id + '&name=' + data.name + '&avater=' + data.avater
		})
		data.tip = 0
		// 更新未读数
		uni.request({
			url: 'http://localhost:7890/yzb/updateMsg',
			data: {
				uid: userid.value,
				fid: data.id
			},
			method: 'POST',
			success: (data) => {
				let code = data.data.code
				if (code == 200) {} else {
					uni.showToast({
						title: "服务器出错啦！",
						icon: "none",
						duration: 2000
					})
				}
			}
		})
	}
	
	
	// 获取好友数据
	const getFrineds = () => {
		userid.value=uni.getStorageSync('userinfo')._id
		uni.request({
			url: 'http://localhost:7890/yzb/getfreind',
			data: {
				uid: userid.value,
			},
			method: 'POST',
			success: (data) => {
				let code = data.data.code
				if (code == 200) {
					let res = data.data.query
					if (res.length > 0) {
						for (let i = 0; i < res.length; i++) {
							List.value.push(res[i])
						}
					}
					List.value = myfun.paixu(List.value, 'lastTime', 0)
					// console.log(List.value);
					// 获取好友内信息
					for (let i = 0; i < List.value.length; i++) {
						getLastMsg(List.value, i)
						getunread(List.value, i)
					}
				} else {
					uni.showToast({
						title: "服务器出错啦！",
						icon: "none",
						duration: 2000
					})
				}
			}
		})
	}
	// 获取最后消息
	const getLastMsg = (arr, i) => {
		uni.request({
			url: 'http://localhost:7890/yzb/getlastmsg',
			data: {
				uid: userid.value,
				fid: arr[i].id
			},
			method: 'POST',
			success: (data) => {
				let code = data.data.code
				if (code == 200) {
					let res = data.data.query
					if (res.types == 0) {
						// 文字
					} else if (res.types == 1) {
						// 图片
						res.message = '[图片]'
					} else if (res.types == 2) {
						// 音频
						res.message = '[音频]'
					} else if (res.types == 3) {
						// 地图位置
						res.message = '[位置]'
					}
					let e = arr[i]
					e.msg = res.message
					arr.splice(i, 1, e)
					// console.log(res);
				} else {
					uni.showToast({
						title: "服务器出错啦！",
						icon: "none",
						duration: 2000
					})
				}
			}
		})
	}
	
	// 获取未读数
	const getunread = (arr, i) => {
		uni.request({
			url: 'http://localhost:7890/yzb/unreadMsg',
			data: {
				uid: userid.value,
				fid: arr[i].id
			},
			method: 'POST',
			success: (data) => {
				let code = data.data.code
				if (code == 200) {
					let res = data.data.query
					let e = arr[i]
					e.tip = res
					arr.splice(i, 1, e)
					// console.log(res);
				} else {
					uni.showToast({
						title: "服务器出错啦！",
						icon: "none",
						duration: 2000
					})
				}
			}
		})
	}
	
	// socket聊天数据接收
	const receiveSocketMsg = () => {
		uni.onSocketMessage(function(res) {
			console.log('收到服务器内容123：' + res.data);
			const msggs = JSON.parse(res.data)
			let nmsg = ''
			if (msggs.types == 0) {
				nmsg = msggs.message
			} else if (msggs.types == 1) {
				nmsg = '[图片]'
			} else if (msggs.types == 2) {
				nmsg = '[音频]'
			} else if (msggs.types == 3) {
				nmsg = '[位置]'
			}
			for (let i = 0; i < List.value.length; i++) {
				if (List.value[i].id == msggs.from) {
					let e = List.value[i]
					e.lastTime = new Date()
					e.msg = nmsg
					e.tip++
					// 删除原来数据项
					List.value.splice(i, 1)
					// 新消息插入到最顶部
					List.value.unshift(e)
					// 更改最后一条消息时间
					uni.request({
						url: 'http://localhost:7890/yzb/updatetime',
						data: {
							uid: userid.value,
							fid: msggs.from
						},
						method: 'POST',
						success: (data) => {
							let code = data.data.code
							if (code == 200) {} else {
								uni.showToast({
									title: "服务器出错啦！",
									icon: "none",
									duration: 2000
								})
							}
						}
					})
				}
			}
		});
	}
</script>

<style lang="scss" scoped>
	.message {
		width: 100vw;
		height: 100vh;
		background-color: aliceblue;

		.data {
			width: 90%;
			height: 70px;
			display: flex;
			margin: 0 auto;
			padding: 10px;
			border: 1px solid #ccc;
			background-color: #fff;
			margin-bottom: 10px;
			border-radius: 5px;

			.image {
				width: 15%;
				border-radius: 50%;
				position: relative;
				.tip {
					color: #fff;
					background: red;
					padding: 5rpx;
					border-radius: 50%;
					position: absolute;
					right: 0;
				}
				.img {
					width: 100%;
					height: 100%;
					border-radius: 10rpx;
				}
			}

			.right {
				width: 75%;
				margin-left: 10px;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.top {
					display: flex;
					justify-content: space-between;

					.tex {
						font-weight: 700;
						font-size: 20px;
					}

					.time {
						color: #636363;
						font-size: 14px;

					}
				}

				.bottom {
					color: #636363;
					margin-bottom: 10px;
				}
			}
		}
	}
</style>